package dalex.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import dalex.command.Command;

import java.sql.*;
import java.util.regex.Pattern;

public class CommandProxy {

	private Connection conn = null;
	
	public CommandProxy(){
		Common.init();
	}
	
	public CommandProxy(Connection conn){
		this.conn = conn;
	}
	
	public void send(String str){
		/*
		 * send将command发送出去
		 * 接收服务器响应字符串
		 * return 响应字符串
		 */
		
		
		Common.init(); 
		String com = str.split(" ")[0];
		System.out.println("proxy.send :"+str) ; 

		Pattern pattern = Pattern.compile("[0-9]*"); 	
		if( pattern.matcher(str).matches() ){
			System.out.println("this is a choice") ; 
			try {
				Common.out.writeInt(Integer.parseInt(str));
				Common.out.flush() ; 
				System.out.println("已发送选择:"+Integer.parseInt(str)) ; 
			} catch (IOException e) {
				e.printStackTrace();
			}
			return ; 
		}else{
			//do nothing
		}
		
		
		
		if(Common.COMMAND.containsKey(com)){
			Command command = Common.COMMAND.get(com) ;
			if(conn == null){
				try{
					command.setCommand(str);
					command.setNickname(Common.nickname) ; 
					//发送请求
					Common.out.writeObject(command);
					System.out.println("command:"+command.getCommand()) ;  //...
					Common.out.flush() ;
					
					System.out.println("commend sent , wait for response .") ; 										
					
					//接收响 应  ， 线程保护。
					/*
					String line = (String) in.readObject() ;						
					while( !line.equals("END") ){							
						if( Common.textArea == null ){
							response.append(line) ; 
						}else{
							Common.textArea.append(line+"\n\n");
						}
						
						line = (String) in.readObject() ; 
					}
					System.out.println("response Received:"+response) ; 
					*/
					
					
				}catch(IOException e){
					e.printStackTrace();
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}else{
				//offline game open DB
				try{
					Statement statement = conn.createStatement();
					command.action();
				}catch(SQLException e){
					e.printStackTrace();
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}
			//command.action(str);
		}else{
			if( Common.textArea == null ){
				System.out.println("什么");
			} else {
				Common.textArea.append("什么\n\n");
			}
		}
		
		//return response.toString() ; 
	}
	
	
	/*
	public void close(){
		if(Common.in != null && Common.out != null ){
			try{
				Common.in.close();
				Common.out.close();
			}catch (IOException e){
				e.printStackTrace();
			}
			
			Common.in = null;
			Common.out = null;
		}else if(conn != null){
			try{
				conn.close();
			}catch (SQLException e){
				e.printStackTrace();
			}
			
			conn = null;
		}else{
			System.out.println("Nothing to be closed!");
		}
	}
	*/
}
